package com.idea.relax.log.trace;

import com.idea.relax.log.constant.PropsConstant;
import com.idea.relax.log.props.RelaxLogProperties;
import com.idea.relax.log.support.utils.StringUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.AllArgsConstructor;
import org.slf4j.MDC;

/**
 * @className: FeignRequestInterceptor
 * @description: feign远程调用时在请求头中追加TraceId
 * @author: salad
 * @date: 2023/1/25
 **/
@AllArgsConstructor
public class FeignRequestInterceptor implements RequestInterceptor {

    private final RelaxLogProperties properties;

    @Override
    public void apply(RequestTemplate template) {
        if (properties.getRequestLog().isEnabledTraceMode()) {
            String traceId = MDC.get(PropsConstant.TRACE_ID);
            String entranceUri = MDC.get(PropsConstant.ENTRANCE_URI);
            template.header(PropsConstant.TRACE_ID_HEADER, StringUtil.isBlank(traceId) ? "N/A" : traceId);
            template.header(PropsConstant.REQ_SOURCE_HEADER, ReqSource.FEIGN.getName());
            template.header(PropsConstant.ENTRANCE_URI_HEADER, entranceUri);
        }
    }

}
